package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
@Slf4j
@RestController
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登陆
     *
     * @param employee
     * @param req
     * @return
     */
    @PostMapping("login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest req) {
        return employeeService.login(req, employee);
    }

    /**
     * 管理员退出
     *
     * @param req
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest req) {
        HttpSession session = req.getSession();
        session.removeAttribute("employee");
        return R.success("退出成功");
    }


    /**
     * 添加管理员
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpServletRequest req) {
        R<String> r = employeeService.SAVE(employee, req);
        return r;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page ipage = employeeService.pageService(page, pageSize, name);
        return R.success(ipage);
    }

    /**
     * 修改用户信息
     *
     * @param employee
     * @param req
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpServletRequest req) {
//        employee.setUpdateUser((Long) req.getSession().getAttribute("employee"));
//        employee.setUpdateTime(LocalDateTime.now());
        log.info("线程{}",Thread.currentThread().getId());
        boolean b = employeeService.updateById(employee);
        return (b ? R.success("修改成功") : R.error("修改失败"));

    }

    /**
     * 查询指定用户
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        return employee!=null ? R.success(employee) : R.error("查询失败");
    }
}
